package com.tutu.user.controller;

import cn.hutool.core.collection.CollUtil;
import com.tutu.commons.checks.AddressSave;
import com.tutu.commons.pojo.Address;
import com.tutu.commons.utils.CollectError;
import com.tutu.commons.utils.R;
import com.tutu.user.service.AddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Program: b2c-cloud-store
 * @Description:
 * @Author: JK.TuTu
 * @ @Version: 1.0
 * @Create: 2022-12-14 11:06
 **/
@Slf4j
@RestController
@RequestMapping("/user/address")
@Api("用户地址相关api")
public class AddressController {

    @Autowired
    private AddressService addressService;


    /**
     * 通过用户id查询地址信息
     *
     * @param userId 用户id
     * @return 返回结果实体对象
     */
    @ApiOperation("根据用户id查询用户地址信息")
    @GetMapping("list/{userId}")
    public R list(@PathVariable(value = "userId", required = true) Integer userId) {
        List<Address> addressList = addressService.getAddressById(userId);
        if (CollUtil.isEmpty(addressList)) {
            return R.fail("该用户下没有地址信息");
        }
        return R.ok(addressList);
    }

    /**
     * 添加地址信息
     *
     * @param address 添加的地址信息
     * @param result  返回检验结果集
     * @return 返回结果实体对象
     */
    @ApiOperation("添加地址信息")
    @PostMapping("/save")
    public R addAddress(@RequestBody @Validated(AddressSave.class) Address address, BindingResult result) {
        log.info("添加的地址信息:{}", address);
        if (result.hasErrors()) {
            String errorInfo = CollectError.getErrorInfo(result);
            return R.fail(errorInfo);
        }
        return addressService.saveAddress(address);
    }

    /**
     * 删除地址
     *
     * @param id 地址信息id
     * @return 返回结果实体对象
     */
    @ApiOperation("删除地址信息")
    @DeleteMapping("remove/{id}")
    public R remove(@PathVariable("id") Integer id) {
        return addressService.remove(id) > 0 ? R.ok("删除成功!") : R.fail("删除失败!");
    }
}
